import random
from io import BytesIO

from flask import request, jsonify, session, redirect, url_for, make_response, current_app
from werkzeug.security import generate_password_hash, check_password_hash

from models import db
from models.index import User, Follow
from utils.aliyunxx import send_note
from utils.captcha.capthca_utils import create_code
from . import passport_blu


# 注册
@passport_blu.route("/register", methods=["POST", "GET"])
def register():
    # 获取数据
    mobile = request.json.get("mobile")
    re_sms_code = request.json.get("smscode")
    image_code = request.json.get("image_code")
    password = request.json.get("password")

    print(re_sms_code)
    print(image_code)

    # 检验数据
        # 检查是否被注册
    if db.session.query(User).filter(User.mobile == mobile).first():
        ret = {"errno":1001,"errmsg":"用户已被注册"}
        return jsonify(ret)

    # 检测 图片验证码
    re_image_code = session.get("captcha_code")

    if not re_image_code == image_code.upper():
        ret = {"errno": 1008, "errmsg": "验证码错误"}
        return jsonify(ret)

    sms_code = session.get("sms_code")

    if not sms_code or sms_code != re_sms_code:
        ret = {
            "errno":"1005",
            "errmsg":"短信验证码有误，重新输入"
        }

        return jsonify(ret)

    password_hash = generate_password_hash(password)
    # 注册用户
    user = User(nick_name=mobile,password_hash=password_hash,mobile=mobile)

    try:
        db.session.add(user)
        db.session.commit()
        ret = {"errno":0,"errmsg":"注册成功"}
        session["nick_name"] = mobile
        session["user_id"] = user.id
    except Exception as e:
        print(e)
        ret = {"errno":1002,"errmsg":"网络错误"}

    # 返回结果
    # ret = {"errno":0,"data":"xx"}
    #
    return jsonify(ret)

# 登录
@passport_blu.route("/login", methods=["POST", "GET"])
def login():

    # 获取数据
    mobile = request.json.get("mobile")
    password = request.json.get("password")

    try:
        # 数据库查验
        user = db.session.query(User).filter(User.mobile==mobile).first()
    except Exception as e:
        print(e)
        ret = {"errno":0000,"errmsg":"网络错误"}

        return jsonify(ret)

    if user and check_password_hash(user.password_hash, password):

        ret = {"errno":0,"errmsg":"登录成功"}

        # 保持登录状态
        session['user_id'] = user.id
        session["nick_name"] = mobile
    else:

        ret = {"errno":1001,"errmsg":"用户名密码错误"}


    return jsonify(ret)

# 退出
@passport_blu.route("/logout")
def logout():

    session.clear()

    return redirect(url_for("index_blu.index"))

# 请求生成图片验证码
@passport_blu.route("/image_code")
def get_image_code():
    # 调用方法拿到数据
    code_str, image = create_code()

    buf = BytesIO()  # 生成 二进制数据对象 直接使用 不用生成图片

    # 把图片数据存到 buf中
    image.save(buf, 'jpeg')

    # 从 buf 里获取 图片的二进制数据
    img_data = buf.getvalue()

    # 创建 response 对象
    ret = make_response(img_data)

    buf.close()

    ret.headers['Content-Type'] = 'image/jpg'

    # 设置session 用来后期验证
    session['captcha_code'] = code_str.upper()

    return ret

# 取消关注用户
@passport_blu.route("/rm_attention")
def rm_attention():

    # 获取登录用户id
    user_id = session.get("user_id")
    # 获取被关注用户id
    f_user_id = session.get("f_user_id")

    try:
        result = db.session.query(Follow).filter(Follow.follower_id == f_user_id,
                                                 Follow.followed_id == user_id).first()
        # 数据库删除数据
        db.session.delete(result)
        db.session.commit()


        ret = {"errno":"0","errmsg":"取消关注成功"}
    except Exception as e:
        print(e)
        ret = {"errno":"2002","errmsg":"网络错误"}


    return jsonify(ret)

# 关注用户
@passport_blu.route("/attention")
def attention():
    # 获取登录用户id
    user_id = session.get("user_id")

    if not user_id:
        ret = {"errno":'1',"errmsg":"请先登录"}
        return jsonify(ret)
    # 获取被关注用户id
    f_user_id = session.get("f_user_id")

    try:
        user = Follow(followed_id=user_id,follower_id=f_user_id)

        # 数据库添加数据
        db.session.add(user)
        db.session.commit()

        ret = {"errno": "0", "errmsg": "关注成功"}
    except Exception as e:
        print(e)
        ret = {"errno": "2002", "errmsg": "网络错误"}

    return jsonify(ret)

# 发送短信验证码
@passport_blu.route("/smscode",methods=["POST"])
def passport_smscode():
    phone = request.json.get("mobile")

    # 3. 生成一个随机的6位数
    sms_code = str(random.randint(100000, 999999))
    print("短信验证码是:", sms_code)

    # 4. 存储到session中
    session['sms_code'] = sms_code

    # 5. 通过短信发送这个6位数
    send_note(phone, sms_code)

    ret = {
        "errno": 0,
        "errmsg": "发送短信验证码成功..."}

    return jsonify(ret)